//
//  ShopListVC.m
//  stone-story
//
//  Created by liu dodo on 12-9-28.
//  Copyright (c) 2012年 liu dodo. All rights reserved.
//

#import "ShopListVC.h"

@interface ShopListVC ()

@end

@implementation ShopListVC
@synthesize resultArray=_resultArray;
@synthesize photos=_photos;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
       _resultArray = [[NSMutableArray alloc] init];
     //[self.view setBackgroundColor:[UIColor grayColor]];
    // 开发在其他地方用这里的方法判断是否第一次
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) 
    {
    [self requestSend];
    }
    else {
        [self mianviewinit];
    }
    
 
    
   
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||interfaceOrientation==UIInterfaceOrientationLandscapeRight  );
}


-(void)mianviewinit
{
    
    [self FMDB_init];
    [self queryTable];
    
    [self tableView_init];
    NSDictionary *cell_text = [_resultArray objectAtIndex:0];
    UIView *shopBGView1=[[UIView alloc] initWithFrame:CGRectMake(260, 5, 720, 670)];
    [shopBGView1 setBackgroundColor:[UIColor grayColor]];
    
    UIView *shopBGView2=[[UIView alloc] initWithFrame:CGRectMake(260, 5, 720, 670)];
    [shopBGView2 setBackgroundColor:[UIColor whiteColor]];
    
    shopBGView1.layer.shadowOffset = CGSizeMake(-5, 3);
    shopBGView1.layer.shadowOpacity = 0.6;
    shopBGView1.layer.shadowColor = [UIColor blackColor].CGColor;
    
    shopBGView2.layer.masksToBounds=YES;
    shopBGView2.layer.cornerRadius=8.0;
    
    
    [self.view addSubview:shopBGView1];
    
    
    UILabel *shopname=[[UILabel alloc]initWithFrame:CGRectMake(10,20, 250, 30)] ;
    [shopname setFont:[UIFont fontWithName:@"Thonburi-Bold" size:20.0]];
    [shopname setTextColor:[UIColor blackColor]];
    [shopname setNumberOfLines:1];
    [shopname setBackgroundColor:[UIColor clearColor]];
    [shopname setTag:1000];
    [shopname setText:[cell_text  objectForKey:@"shop_name"]];
    [shopBGView2 addSubview:shopname];
    
    UIImageView *newsline=[[UIImageView alloc] initWithFrame:CGRectMake(10, 65, 700, 1)];
    [newsline setBackgroundColor:[UIColor clearColor]];
    [newsline setImage:[UIImage imageNamed:@"ZS_line.png"]];
    [shopBGView2 addSubview:newsline];
    
    photospath=[cell_text  objectForKey:@"shop_photos_path"];
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:photospath];
    
    NSLog(@"%@",filePath);
    UIImage *myimage=[UIImage imageWithContentsOfFile:[filePath stringByAppendingPathComponent:@"logos/1.jpg"]];
    
    UIImageView *shopbanner=[[UIImageView alloc] initWithFrame:CGRectMake(10, 70, 700, 200)];
    shopbanner.backgroundColor=[UIColor clearColor];
    if (myimage) {
        [shopbanner setImage:myimage];
    }
    else
    {
        [shopbanner setImage:[UIImage imageNamed:@"defaultbanner.png"]];
    }
    
    [shopbanner setTag:1001];
    [shopBGView2 addSubview:shopbanner];
    
    
    UILabel *shopContacts=[[UILabel alloc]initWithFrame:CGRectMake(10,shopbanner.frame.origin.y+shopbanner.frame.size.height+5, 250, 30)] ;
    [shopContacts setFont:[UIFont fontWithName:@"Thonburi-Bold" size:18.0]];
    [shopContacts setTextColor:[UIColor blackColor]];
    [shopContacts setNumberOfLines:1];
    [shopContacts setBackgroundColor:[UIColor clearColor]];
    [shopContacts setText:@"联系方式"];
    [shopBGView2 addSubview:shopContacts];
    
    
    UILabel *shopContactsdetail=[[UILabel alloc]initWithFrame:CGRectMake(10,shopContacts.frame.origin.y+shopContacts.frame.size.height, 55, 100)] ;
    [shopContactsdetail setFont:[UIFont fontWithName:@"Thonburi-Bold" size:16.0]];
    [shopContactsdetail setTextColor:[UIColor blackColor]];
    [shopContactsdetail setNumberOfLines:5];
    [shopContactsdetail setBackgroundColor:[UIColor clearColor]];
    [shopContactsdetail setText:@"地   址:电   话:邮   箱:联系人:"];
    [shopBGView2 addSubview:shopContactsdetail];
    
    
    UILabel *shopaddress=[[UILabel alloc]initWithFrame:CGRectMake(10+shopContactsdetail.frame.size.width+5,shopContactsdetail.frame.origin.y+10, 600, 20)] ;
    [shopaddress setFont:[UIFont fontWithName:@"Thonburi-Bold" size:16.0]];
    [shopaddress setTextColor:[UIColor blackColor]];
    [shopaddress setNumberOfLines:1];
    [shopaddress setBackgroundColor:[UIColor clearColor]];
    [shopaddress setTag:1002];
    [shopaddress setText:[cell_text  objectForKey:@"shop_addr"]];
    [shopBGView2 addSubview:shopaddress];
    
    
    UILabel *shoptelphone=[[UILabel alloc]initWithFrame:CGRectMake(shopaddress.frame.origin.x,shopaddress.frame.origin.y+shopaddress.frame.size.height, 600, 20)] ;
    [shoptelphone setFont:[UIFont fontWithName:@"Thonburi-Bold" size:16.0]];
    [shoptelphone setTextColor:[UIColor blackColor]];
    [shoptelphone setNumberOfLines:1];
    [shoptelphone setBackgroundColor:[UIColor clearColor]];
    [shoptelphone setTag:1003];
    [shoptelphone setText:[cell_text  objectForKey:@"shop_tel"]];
    [shopBGView2 addSubview:shoptelphone];
    
    UILabel *shopemail=[[UILabel alloc]initWithFrame:CGRectMake(shoptelphone.frame.origin.x,shoptelphone.frame.origin.y+shoptelphone.frame.size.height, 600, 20)] ;
    [shopemail setFont:[UIFont fontWithName:@"Thonburi-Bold" size:16.0]];
    [shopemail setTextColor:[UIColor blackColor]];
    [shopemail setNumberOfLines:1];
    [shopemail setBackgroundColor:[UIColor clearColor]];
    [shopemail setTag:1004];
    [shopemail setText:[cell_text  objectForKey:@"shop_email"]];
    [shopBGView2 addSubview:shopemail];
    
    UILabel *shopelinkman=[[UILabel alloc]initWithFrame:CGRectMake(shopemail.frame.origin.x,shopemail.frame.origin.y+shopemail.frame.size.height, 600, 20)] ;
    [shopelinkman setFont:[UIFont fontWithName:@"Thonburi-Bold" size:16.0]];
    [shopelinkman setTextColor:[UIColor blackColor]];
    [shopelinkman setNumberOfLines:1];
    [shopelinkman setBackgroundColor:[UIColor clearColor]];
    [shopelinkman setTag:1005];
    [shopelinkman setText:[cell_text  objectForKey:@"shop_linkman"]];
    [shopBGView2 addSubview:shopelinkman];
    
    UILabel *shopInfo=[[UILabel alloc]initWithFrame:CGRectMake(10,shopContactsdetail.frame.origin.y+shopContactsdetail.frame.size.height+5, 250, 30)] ;
    [shopInfo setFont:[UIFont fontWithName:@"Thonburi-Bold" size:18.0]];
    [shopInfo setTextColor:[UIColor blackColor]];
    [shopInfo setNumberOfLines:1];
    [shopInfo setBackgroundColor:[UIColor clearColor]];
    [shopInfo setText:@"公司介绍"];
    [shopBGView2 addSubview:shopInfo];
    
    //添加新闻条目的具体内容(取备注 以防止有HTML代码)
    UILabel *shopInfoContent=[[UILabel alloc]initWithFrame:CGRectMake(shopInfo.frame.origin.x+5,shopInfo.frame.origin.y+shopInfo.frame.size.height, 650, 300)] ;
    [shopInfoContent setFont:[UIFont fontWithName:@"Thonburi-Bold" size:16.0]];
    [shopInfoContent setTextColor:[UIColor blackColor]];
    [shopInfoContent setNumberOfLines:8];
    [shopInfoContent setBackgroundColor:[UIColor clearColor]];
    [shopInfoContent setText:[cell_text  objectForKey:@"shop_info"]];
    [self setAligTop:shopInfoContent whithint:8 whithmaxhith:200];
    [shopInfoContent setTag:1006];
    [shopBGView2 addSubview:shopInfoContent];
    
    
    
    //按钮
    
    UIButton *myBtn = [[UIButton alloc]init];
    [myBtn setFrame:CGRectMake(420,600,259,49)];
    [myBtn setBackgroundImage:[UIImage imageNamed:@"photos_btn.png"] forState:UIControlStateNormal];
    [myBtn addTarget:self action:@selector(onmyBtn_Click) forControlEvents:UIControlEventTouchUpInside];
    [myBtn.titleLabel setTextColor:[UIColor blackColor]];
    
    [myBtn setTitle:@"查看店面相册" forState:UIControlStateNormal];
    [myBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
    [myBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [myBtn setBackgroundColor:[UIColor clearColor]];
    
    [shopBGView2 addSubview:myBtn];
    
    [self.view addSubview:shopBGView2];
}

//创建左边TABLEVIEW
- (void)tableView_init
{
    CGRect tableFrame=CGRectMake(0,48,260,600); //矩形结构
    ShopListTableView=[[UITableView alloc]initWithFrame:tableFrame]; //分配内存，设置样式
    [ShopListTableView setDelegate:self]; //设置代理
    [ShopListTableView setDataSource:self]; //设置数据源
    [ShopListTableView setBackgroundColor:[UIColor whiteColor]];
    [ShopListTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    //[ShopListTableView setAllowsSelection:NO];
  
    [self.view addSubview:ShopListTableView]; //添加到父视图
    
}




#pragma mark - 数据库操作
//创建或打开数据库
- (void)FMDB_init//1
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    
    //dbPath： 数据库路径，在Document中。
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"db_stoneStory.db"];
    
    //创建数据库实例 db  这里说明下:如果路径中不存在"Test.db"的文件,sqlite会自动创建"Test.db"
    db= [FMDatabase databaseWithPath:dbPath];
    if (![db open])
    {
        NSLog(@"Could not open db.");
        return ;
    }
    else
    {
        NSLog(@"open db. success!");
    }
    
    
    
}



//查询表格 把结果付给_resultArray
- (void)queryTable
{
    //返回数据库中第一条满足条件的结果
    //   NSString *aa=[db stringForQuery:@"SELECT Name FROM User WHERE Age = ?",@"20"];
    FMResultSet *rs =[db executeQuery:@"SELECT * FROM tb_shops"];
    int columns= [rs columnCount];
    while ([rs next])
    {
       NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
       for (int i=0; i<columns; i++)
       {
           NSLog(@"the %@ is :%@",[rs columnNameForIndex:i],[rs stringForColumnIndex:i]);
           [item setObject:[rs stringForColumnIndex:i] forKey:[rs columnNameForIndex:i]];     
       }
       [ _resultArray addObject:item];   
            
    }
    
    [rs close];
    [db close];
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    return [_resultArray count];
}

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 102.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    // Configure the cell...
    NSDictionary *cell_text = [_resultArray objectAtIndex:indexPath.row];
    
    
    //cell.textLabel.text=[cell_text  objectForKey:@"shop_name"];
    
    /*
    //添加新闻条目的背景图片
    
    UIImageView *BG=[[UIImageView alloc] initWithFrame:CGRectMake(10, 1, 300, 100)];
    BG.backgroundColor=[UIColor clearColor];
    BG.image =[UIImage imageNamed:@"zs_news.png"];
    
    [cell.contentView addSubview:BG];
    */
    
    //添加商店的80*80标题图
    
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/shops/"];
    filePath=[filePath stringByAppendingPathComponent:[cell_text  objectForKey:@"shop_code"]];
    filePath=[filePath stringByAppendingPathComponent:@"logos"];
   
    UIImage *myimage=[UIImage imageWithContentsOfFile:[filePath stringByAppendingPathComponent:@"0.png"]];
    
    UIImageView *shoplogo=[[UIImageView alloc] initWithFrame:CGRectMake(20, 11, 80, 80)];
    shoplogo.backgroundColor=[UIColor clearColor];
    
    if (myimage) {
        [shoplogo setImage:myimage];

    }
    else
    {
        [shoplogo setImage:[UIImage imageNamed:@"shopsdefaultlogo.png"]];
    }
        [cell.contentView addSubview:shoplogo];
    
    CALayer *l = [shoplogo layer];   //获取ImageView的层
    [l setMasksToBounds:YES];
    [l setCornerRadius:8.0];
    
    //添加商店的名称的标题
    UILabel *lb_shopname=[[UILabel alloc]initWithFrame:CGRectMake(shoplogo.frame.origin.x
                                                                +shoplogo.frame.size.width+8,11, 150, 30)] ;
    [lb_shopname setFont:[UIFont fontWithName:@"Thonburi-Bold" size:16.0]];
    [lb_shopname setTextColor:[UIColor blackColor]];
    [lb_shopname setNumberOfLines:1];
    [lb_shopname setBackgroundColor:[UIColor clearColor]];
    [lb_shopname setText:[cell_text  objectForKey:@"shop_name"]];
    [cell.contentView addSubview:lb_shopname];
    
    
    //添加新闻条目的具体内容(取备注 以防止有HTML代码)
    UILabel *lb_shopcontent=[[UILabel alloc]initWithFrame:CGRectMake(lb_shopname.frame.origin.x,lb_shopname.frame.origin.y+lb_shopname.frame.size.height, 150, 50)] ;
    [lb_shopcontent setFont:[UIFont fontWithName:@"Thonburi-Bold" size:12.0]];
    [lb_shopcontent setTextColor:[UIColor grayColor]];
    
    [lb_shopcontent setNumberOfLines:3];
    [lb_shopcontent setBackgroundColor:[UIColor clearColor]];
    
    
    [lb_shopcontent setText:[cell_text  objectForKey:@"shop_addr"]];
    [self setAligTop:lb_shopcontent whithint:3 whithmaxhith:50];
    [cell.contentView addSubview:lb_shopcontent];
    
    
    cell.selectionStyle=UITableViewCellSelectionStyleGray;
    
    return cell;
}

//将label文本垂直置顶
-(void)setAligTop:(UILabel *)label whithint:(NSInteger) I whithmaxhith:(CGFloat) height
{
    label.numberOfLines=I;
    CGSize maxSize= CGSizeMake(label.frame.size.width, height);
    label.adjustsFontSizeToFitWidth = NO;
    
    // get actual height
    CGSize actualSize=[label.text sizeWithFont:label.font constrainedToSize:maxSize lineBreakMode:label.lineBreakMode];
    CGRect rect=label.frame;
    rect.size.height=actualSize.height;
    
    label.frame=rect;
    
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     NSDictionary *cell_text = [_resultArray objectAtIndex:indexPath.row];
    
    UILabel *r_shop_name=(UILabel *)[self.view viewWithTag:1000];
    [r_shop_name setText:[cell_text  objectForKey:@"shop_name"]];
    
    UILabel *r_shop_addr=(UILabel *)[self.view viewWithTag:1002];
    [r_shop_addr setText:[cell_text  objectForKey:@"shop_addr"]];
    
    UILabel *r_shop_tel=(UILabel *)[self.view viewWithTag:1003];
    [r_shop_tel setText:[cell_text  objectForKey:@"shop_tel"]];
    
    UILabel *r_shop_email=(UILabel *)[self.view viewWithTag:1004];
    [r_shop_email setText:[cell_text  objectForKey:@"shop_email"]];
    
    UILabel *r_shop_linkman=(UILabel *)[self.view viewWithTag:1005];
    [r_shop_linkman setText:[cell_text  objectForKey:@"shop_linkman"]];
    
    UILabel *r_shop_info=(UILabel *)[self.view viewWithTag:1006];
    [r_shop_info setText:[cell_text  objectForKey:@"shop_info"]];
    [self setAligTop:r_shop_info whithint:8 whithmaxhith:200];
    
    photospath=[cell_text  objectForKey:@"shop_photos_path"];
    
    UIImageView *r_shop_banner=(UIImageView *)[self.view viewWithTag:1001];
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:[cell_text  objectForKey:@"shop_photos_path"]];
    
    UIImage *myimage=[UIImage imageWithContentsOfFile:[filePath stringByAppendingPathComponent:@"logos/1.jpg"]];
    if (myimage) {
        [r_shop_banner setImage:myimage];
    }
    else
    {
        [r_shop_banner setImage:[UIImage imageNamed:@"defaultbanner.png"]];
    }
}


-(void)onmyBtn_Click
{
     [self goToPhotoBrowserWithPath:photospath];
}


#pragma mark 相册部分 根据目录去到相册
-(void)goToPhotoBrowserWithPath:(NSString*)pathString
{
    NSMutableArray *photos = [[NSMutableArray alloc] init];
    MWPhoto *photo;
    lf=[[LCFileManager alloc] init];
    
    NSMutableArray *photosArray=[lf getAllPhotosWithPath:pathString];
    
    //[self getAllPhotosWithPath:pathString];
    for(int i=0;i<photosArray.count;i++)
    {
        //Documents/productPhotos/
        NSString *fullPath=[pathString stringByAppendingString:[photosArray objectAtIndex:i]];
        photo = [MWPhoto photoWithFilePath:[NSHomeDirectory() stringByAppendingPathComponent:fullPath]];
        //photo.caption = @"Grotto of the Madonna";
        [photos addObject:photo];
    }
    self.photos = photos;
	MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = YES;
    //browser.wantsFullScreenLayout = NO;//[browser setInitialPageIndex:2];
    [self.navigationController pushViewController:browser animated:YES];
}

#pragma mark - 相册部分 委托

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return _photos.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photos.count)
        return [_photos objectAtIndex:index];
    return nil;
}








#pragma mark 初始化数据请求
- (void)requestSend
{
    [self HUD_Create:self.view];
     [self HUD_Show];
    [self setRootNodeName:@"shop"];
    [self request_Send:ShopsAPI withPostArg:nil];
    
}

//调用父类请求[成功]时的方法
- (void)getResultArraySuccess //请求回来并解释好的数据都放在[resultArray]这个数组中,直接引用
{
    [self HUD_Hide];
    haveConnect=YES;
    NSLog(@"[result count is aaa := %d]",resultArray.count);
    
    
    lf=[[LCFileManager alloc]init];
    lf.delegate=self;
    
    for (NSMutableDictionary* dict in resultArray)
    {
        NSArray *urlArray=[[dict objectForKey:@"shop_photos"] componentsSeparatedByString:@","];
        
        [lf downLoadFilesWithUrlArray:urlArray UIProgressView:nil queueIdentifier:[dict objectForKey:@"shop_code"]saveToPath:@"Documents/shops/" folderName:[dict objectForKey:@"shop_code"]];
    }
    for (NSMutableDictionary* dict in resultArray)
    {
        
        
        NSArray *urlArray=[NSArray arrayWithObjects:[dict objectForKey:@"shop_smalllogo"],[dict objectForKey:@"shop_logo"], nil];
        
        [lf downLoadFilesWithUrlArray:urlArray UIProgressView:nil queueIdentifier:[dict objectForKey:@"shop_code"]
                           saveToPath:[@"Documents/shops/" stringByAppendingString:[dict objectForKey:@"shop_code"]]  folderName:@"logos"];
    }
    
    [self DataInsertToDB];
    
    
}
//调用父类请求[失败]时的方法
- (void)requestError
{
    NSLog(@"发送请求失败");
   [self HUD_Hide];
}

#pragma mark - 图片下载完成代理方法
-(void)queueFilish:(NSString *)queueIdentifier
{
    NSLog(@"the queue indetifier is:%@",queueIdentifier);
}



#pragma mark - 初始化datebase
//数据入库操作
-(void)DataInsertToDB
{
    [self FMDB_OPEN];//打开数据
    [self createTable];//创建表
    [self deleteRecord];//清空表数据
    //插入数据
    for (NSMutableDictionary* dict in resultArray) {
        
        if([self isExistTable:@"tb_shops" InTheDateBase:db]){
            
            NSString *shop_photospath=[@"Documents/shops/" stringByAppendingPathComponent:[dict objectForKey:@"shop_code"]];
            [db executeUpdate:@"INSERT INTO tb_shops VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[dict objectForKey:@"shop_code"],[dict objectForKey:@"shop_name"],[dict objectForKey:@"shop_info"],[dict objectForKey:@"shop_level"],[dict objectForKey:@"shop_logo"],[dict objectForKey:@"shop_smalllogo"],[dict objectForKey:@"shop_linkman"],[dict objectForKey:@"shop_tel"],[dict objectForKey:@"shop_email"],[dict objectForKey:@"shop_addr"],[dict objectForKey:@"shop_note"],[dict objectForKey:@"shop_type"],[dict objectForKey:@"shop_owner"],[dict objectForKey:@"shop_city"],[dict objectForKey:@"shop_province"],[dict objectForKey:@"shop_area"],[shop_photospath stringByAppendingString:@"/"]];
            
        }
        else {
            NSLog(@"table db.Products have not exist!");
        }
        
    }
    
    
    [self mianviewinit];

    
}




//创建或打开数据库
- (void)FMDB_OPEN//1
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    
    //dbPath： 数据库路径，在Document中。
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"db_stoneStory.db"];
    
    //创建数据库实例 db  这里说明下:如果路径中不存在"Test.db"的文件,sqlite会自动创建"Test.db"
    db= [FMDatabase databaseWithPath:dbPath];
    if (![db open]) {
        NSLog(@"Could not open db.");
        return ;
    }
    else {
        NSLog(@"open db. success!");
    }
    
    
    
}
//创建表
- (void)createTable
{
    //创建一个名为User的表，四个字段 书的ID,书的图片文件名,书的pdf文件名,书的排号
    if(![self isExistTable:@"tb_shops" InTheDateBase:db])
        [db executeUpdate:@"CREATE TABLE tb_shops (shop_code text,shop_name text,shop_info text,shop_level text,shop_logo text,shop_smalllogo text,shop_linkman text,shop_tel text,shop_email text,shop_addr text,shop_note text,shop_type text,shop_owner text,shop_city text,shop_province text,shop_area text,shop_photos_path text)"];
    else {
        NSLog(@"table tb_shops have exist!");
    }
}


//删除数据
- (void)deleteRecord
{
    if([self isExistTable:@"tb_shops" InTheDateBase:db])
    {
        [db executeUpdate:@"DELETE FROM tb_shops "];
    }
    else
    {
        NSLog(@"table tb_shops have not exist!");
    }
}




//判断是否存在该表
-(BOOL)isExistTable:(NSString*)tablename InTheDateBase:(FMDatabase *)tdb {
    
    FMResultSet *rs = [tdb executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", tablename];
    while ([rs next])
    {
        // just print out what we've got in a number of formats.
        NSInteger count = [rs intForColumn:@"count"];
        NSLog(@"isTableOK %d", count);
        
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    
    return NO;
}



@end
